package com.chj.configs;

import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

@Configuration
public class RabbitMQConfig {

    @Value("chj.dead-letter.fanout." + "${spring.application.name}")
    private String dlxName;
    @Value("chj.dead-letter.queue." + "${spring.application.name}")
    private String dlqName;

    public String getDlxName() {
        return dlxName;
    }

    @Bean
    public MessageConverter jsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    @Bean
    @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    // 由于消息确认回调实现可能不一样，因此使用PROTOTYPE
    public RabbitTemplate rabbitTemplate(ConnectionFactory connFactory) {
        RabbitTemplate template = new RabbitTemplate(connFactory);
        template.setMessageConverter(jsonMessageConverter());
        return template;
    }

    @Bean
    public RabbitAdmin admin(ConnectionFactory connFactory) {
        RabbitAdmin admin = new RabbitAdmin(connFactory);
        admin.setIgnoreDeclarationExceptions(true);
        return admin;
    }
}
